/**
 * VacationController
 *
 * @description :: Server-side logic for managing Vacations
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */
var moment = require('moment');

module.exports = {
	
	vacations : function(req, res){
		
		var owner = req.session.user.userid;
		var year = req.param("current");
		var action = req.param("action");
		var dateYear = FormService.getYearByAction(year, action);
		
		LeaveNote.find({
			'startTime': { '>=': dateYear.current.toDate(), '<': dateYear.next.toDate() },
			'type':sails.config.application.vacationType,
		})
		.sort('startTime ASC')
		.populate('form')
		.then(function (notes) {
			
			Vacation.findOne({'owner':owner})
			.then(function (myvaca) {
				if(myvaca == undefined){
					myvaca = {hours:0}
				}
				var vacations = [];
				for (var i = 0; i < notes.length; i++) {
					//finish & mine
					if(notes[i].form.state == 3 && notes[i].form.owner == owner){
						var hours = notes[i].hours;
						var month = moment(notes[i].startTime).format("MM");
						month = parseInt(month);
						
						if(vacations[month] == undefined){
							vacations[month] = hours;
						}else{
							vacations[month] += hours;
						}
					}
				}
				
				return res.view('mobile/vacations', {
					vacations : vacations,
					current : dateYear.current.format("YYYY"),
					left : myvaca.hours
				});
				
			});
			
		}).catch(function(err){
			sails.log.error(err);
			return res.serverError(err);
		});
	},
	
	check : function(req, res){
		var owner = req.session.user.userid;
		var hours = req.param("hours");
		var type = req.param("type");
		
		if(type != sails.config.application.vacationType){
			return res.send({
				success : true,
				result : true
			});
		}
		
		Vacation.findOne({'owner' : owner})
		.then(function (vaca) {
			var result = true;
			if(vaca == undefined || parseInt(hours) > parseInt(vaca.hours)){
				result = false;
			}
			return res.send({
				success : true,
				result : result
			});
		}).catch(function(err){
			sails.log.error(err);
			return res.send({
				success : false,
				error : err
			});
		});
	}
};

